import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * 有序表
 */
public class TreeSetAndTreeMap {
    public static void main(String[] args) {
        //底层是红黑树
        TreeMap<Integer,String> treeMap = new TreeMap<>();
        treeMap.put(2,"这是2");
        treeMap.put(3,"这是3");
        treeMap.put(4,"这是4");
        treeMap.put(6,"这是6");
        treeMap.put(8,"这是8");
        treeMap.put(1,"这是1");

        System.out.println(treeMap.containsKey(2));
        System.out.println(treeMap.containsKey(10));
        treeMap.put(4,"我是张山");
        System.out.println(treeMap.get(4));

        //第一个key
        System.out.println(treeMap.firstKey());
        //最后一个key
        System.out.println(treeMap.lastKey());

        //<=7最近的那个key
        System.out.println(treeMap.floorKey(7));
        //>=7最近的那个key
        System.out.println(treeMap.ceilingKey(7));


        System.out.println("=======================");


        TreeSet<Integer> set = new TreeSet<>();
        set.add(3);
        set.add(3);
        set.add(4); //也会去重
        System.out.println(set.size());
        while (!set.isEmpty()) {
            System.out.println(set.pollFirst());
        }
        System.out.println("=======================");

        //有序表 优先级队列 底层默认为小根堆
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        heap.add(9);
        heap.add(4);
        heap.add(8);
        heap.add(9);
        heap.add(9);//不会去重
        System.out.println(heap.size());
        while (!heap.isEmpty()) {
            System.out.println(heap.poll());
        }
        System.out.println("=======================");

        //构造器指定如何排序
        PriorityQueue<Integer> heap2 = new PriorityQueue<>((a,b) -> b-a);
        heap2.add(4);
        heap2.add(0);
        heap2.add(8);
        heap2.add(5);
        while (!heap2.isEmpty()) {
            System.out.println(heap2.poll());
        }
    }
}
